/**
 * 主要JavaScript文件 - 处理通用功能
 * 突袭简历 - AI智能简历优化平台
 */

// 应用主类
class SuperCVApp {
    constructor() {
        this.currentUser = null;
        this.isLoggedIn = false;
        this.init();
    }

    // 初始化应用
    async init() {
        this.setupEventListeners();
        this.setupMobileMenu();
        await this.checkAuthStatus();
        this.updateUI();
    }

    // 设置事件监听器
    setupEventListeners() {
        // 页面加载完成后的处理
        document.addEventListener('DOMContentLoaded', () => {
            this.initTooltips();
            this.initModals();
        });

        // 登出功能
        document.addEventListener('click', (e) => {
            if (e.target.matches('.logout-btn')) {
                e.preventDefault();
                this.logout();
            }
        });

        // 需要登录的链接处理
        document.addEventListener('click', (e) => {
            if (e.target.matches('.require-login')) {
                e.preventDefault();
                if (!this.isLoggedIn) {
                    this.showLoginPrompt();
                } else {
                    window.location.href = e.target.href;
                }
            }
        });
    }

    // 设置移动端菜单
    setupMobileMenu() {
        const mobileToggle = document.querySelector('.mobile-menu-toggle');
        const mainNav = document.querySelector('.main-nav');
        
        if (mobileToggle && mainNav) {
            mobileToggle.addEventListener('click', () => {
                mainNav.classList.toggle('active');
                mobileToggle.classList.toggle('active');
            });

            // 点击菜单项后关闭移动菜单
            mainNav.addEventListener('click', (e) => {
                if (e.target.matches('a')) {
                    mainNav.classList.remove('active');
                    mobileToggle.classList.remove('active');
                }
            });
        }
    }

    // 检查认证状态
    async checkAuthStatus() {
        const token = localStorage.getItem('auth_token');
        const uid = localStorage.getItem('uid');
        
        if (token && uid) {
            try {
                this.currentUser = await apiClient.getUserInfo();
                this.isLoggedIn = true;
            } catch (error) {
                console.error('获取用户信息失败:', error);
                this.clearAuth();
            }
        }
    }

    // 更新UI状态
    updateUI() {
        const userActions = document.querySelector('.user-actions');
        if (!userActions) return;

        if (this.isLoggedIn && this.currentUser) {
            // 已登录状态
            userActions.innerHTML = `
                <div class="user-menu">
                    <button class="user-avatar" onclick="toggleUserDropdown()">
                        <img src="${this.currentUser.avatar || '/images/default-avatar.svg'}" alt="${this.currentUser.nickname || '用户'}">
                        <span>${this.currentUser.nickname || '用户'}</span>
                        <i class="icon-chevron-down"></i>
                    </button>
                    <div class="user-dropdown" id="userDropdown">
                        <a href="dashboard.html" class="dropdown-item">
                            <i class="icon-dashboard"></i>
                            <span>工作台</span>
                        </a>
                        <a href="my-resumes.html" class="dropdown-item">
                            <i class="icon-resume"></i>
                            <span>我的简历</span>
                        </a>
                        <a href="account-settings.html" class="dropdown-item">
                            <i class="icon-settings"></i>
                            <span>账户设置</span>
                        </a>
                        <div class="dropdown-divider"></div>
                        <button class="dropdown-item logout-btn">
                            <i class="icon-logout"></i>
                            <span>退出登录</span>
                        </button>
                    </div>
                </div>
            `;
        } else {
            // 未登录状态
            userActions.innerHTML = `
                <a href="login.html" class="btn btn-login">登录</a>
                <a href="register.html" class="btn btn-primary">注册</a>
            `;
        }
    }

    // 登出
    logout() {
        this.clearAuth();
        this.showToast('已成功退出登录', 'success');
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 1000);
    }

    // 清除认证信息
    clearAuth() {
        apiClient.clearAuth();
        this.currentUser = null;
        this.isLoggedIn = false;
        this.updateUI();
    }

    // 显示登录提示
    showLoginPrompt() {
        this.showModal({
            title: '需要登录',
            content: '请先登录后再使用此功能',
            buttons: [
                {
                    text: '取消',
                    class: 'btn-secondary',
                    action: 'close'
                },
                {
                    text: '立即登录',
                    class: 'btn-primary',
                    action: () => {
                        window.location.href = 'login.html';
                    }
                }
            ]
        });
    }

    // 显示Toast提示
    showToast(message, type = 'info', duration = 3000) {
        // 创建toast容器（如果不存在）
        let toastContainer = document.querySelector('.toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.className = 'toast-container';
            document.body.appendChild(toastContainer);
        }

        // 创建toast元素
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.innerHTML = `
            <div class="toast-content">
                <i class="toast-icon icon-${this.getToastIcon(type)}"></i>
                <span class="toast-message">${message}</span>
                <button class="toast-close" onclick="this.parentElement.parentElement.remove()">
                    <i class="icon-close"></i>
                </button>
            </div>
        `;

        // 添加到容器
        toastContainer.appendChild(toast);

        // 显示动画
        setTimeout(() => {
            toast.classList.add('show');
        }, 100);

        // 自动隐藏
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                if (toast.parentElement) {
                    toast.remove();
                }
            }, 300);
        }, duration);
    }

    // 获取Toast图标
    getToastIcon(type) {
        const icons = {
            success: 'check-circle',
            error: 'x-circle',
            warning: 'alert-triangle',
            info: 'info-circle'
        };
        return icons[type] || icons.info;
    }

    // 显示模态框
    showModal(options) {
        const modal = document.createElement('div');
        modal.className = 'modal-overlay';
        modal.innerHTML = `
            <div class="modal-container">
                <div class="modal-header">
                    <h3 class="modal-title">${options.title}</h3>
                    <button class="modal-close" onclick="this.closest('.modal-overlay').remove()">
                        <i class="icon-close"></i>
                    </button>
                </div>
                <div class="modal-content">
                    ${options.content}
                </div>
                <div class="modal-footer">
                    ${options.buttons.map(btn => `
                        <button class="btn ${btn.class}" onclick="${btn.action === 'close' ? 'this.closest(\'.modal-overlay\').remove()' : btn.action}">
                            ${btn.text}
                        </button>
                    `).join('')}
                </div>
            </div>
        `;

        document.body.appendChild(modal);
        document.body.style.overflow = 'hidden';

        // 显示动画
        setTimeout(() => {
            modal.classList.add('active');
        }, 100);

        // 点击背景关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.remove();
                document.body.style.overflow = '';
            }
        });
    }

    // 初始化工具提示
    initTooltips() {
        const tooltipElements = document.querySelectorAll('[data-tooltip]');
        tooltipElements.forEach(element => {
            element.addEventListener('mouseenter', this.showTooltip);
            element.addEventListener('mouseleave', this.hideTooltip);
        });
    }

    // 显示工具提示
    showTooltip(e) {
        const text = e.target.getAttribute('data-tooltip');
        const tooltip = document.createElement('div');
        tooltip.className = 'tooltip';
        tooltip.textContent = text;
        document.body.appendChild(tooltip);

        const rect = e.target.getBoundingClientRect();
        tooltip.style.left = rect.left + rect.width / 2 - tooltip.offsetWidth / 2 + 'px';
        tooltip.style.top = rect.top - tooltip.offsetHeight - 8 + 'px';

        setTimeout(() => {
            tooltip.classList.add('show');
        }, 100);

        e.target._tooltip = tooltip;
    }

    // 隐藏工具提示
    hideTooltip(e) {
        if (e.target._tooltip) {
            e.target._tooltip.remove();
            e.target._tooltip = null;
        }
    }

    // 初始化模态框
    initModals() {
        // 通用模态框关闭功能
        document.addEventListener('click', (e) => {
            if (e.target.matches('.modal-close') || e.target.closest('.modal-close')) {
                const modal = e.target.closest('.modal-overlay');
                if (modal) {
                    modal.remove();
                    document.body.style.overflow = '';
                }
            }
        });

        // ESC键关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                const modal = document.querySelector('.modal-overlay');
                if (modal) {
                    modal.remove();
                    document.body.style.overflow = '';
                }
            }
        });
    }
}

// 全局函数
function toggleUserDropdown() {
    const dropdown = document.getElementById('userDropdown');
    if (dropdown) {
        dropdown.classList.toggle('show');
    }
}

// 点击外部关闭下拉菜单
document.addEventListener('click', (e) => {
    if (!e.target.closest('.user-menu')) {
        const dropdown = document.getElementById('userDropdown');
        if (dropdown) {
            dropdown.classList.remove('show');
        }
    }
});

// 初始化应用
const app = new SuperCVApp();

// 导出应用实例
window.superCVApp = app;